#!/bin/bash

set -Eeuo pipefail
# no shopt -s inherit_errexit as not supported in the build-python3.8 container

cd "$(dirname "${BASH_SOURCE[0]}")/../../.."
ROOT_DIR=${PWD}

ZIP_FILE=${ROOT_DIR}/webhook_receiver_lambda.zip
rm -f "${ZIP_FILE}"

PACKAGE_DIR="$(mktemp -d)"
TEST_DIR="$(mktemp -d)"
trap 'rm -rf "${PACKAGE_DIR}" "${TEST_DIR}"' EXIT

# Install cki-tools
python3 -m pip install --no-deps "${ROOT_DIR}" --target "${PACKAGE_DIR}"

# Install minimal dependencies to get webhook-receiver working
pip_url=git+https://gitlab.com/cki-project/cki-lib.git@production
if [[ -v cki_lib_pip_url ]]; then
    pip_url=${cki_lib_pip_url}
    echo "Found cki-lib override: ${pip_url}"
fi
python3 -m pip install --no-deps "${pip_url}" --target "${PACKAGE_DIR}"
python3 -m pip install urllib3 sentry-sdk prometheus_client pika python-gitlab python-dateutil pyyaml gql jsonschema[format] --target "${PACKAGE_DIR}"

# RabbitMQ certificate
curl --location --silent --fail --show-error https://gitlab.com/cki-project/containers/-/raw/production/files/rh-cki.crt > "${PACKAGE_DIR}/rh-cki.crt"

# Package without the venv
pushd "${PACKAGE_DIR}"
    zip -r9 "${ZIP_FILE}" .
popd

# Prepare a venv to ignore system packages
python3 -m venv "${TEST_DIR}"

# Test the package
pushd "${TEST_DIR}"
    unzip "${ZIP_FILE}"
    if ! PYTHONPATH=. bin/python3 cki/cki_tools/webhook_receiver/lambdas.py; then
        echo "Lambda could not be started, deleting ZIP file"
        rm "${ZIP_FILE}"
        exit 1
    fi
popd

echo "Successfully built webhook-receiver ZIP file in ${ZIP_FILE}"
